import website from '@/config/website';
import { validatenull } from '@/utils/validate';
import type { paramsType } from '@/types/store';
const keyName = website.key + '-';
/**
 * 默认存储localStorage
 */
export const setStore = (params: paramsType) => {
    const { name, content, type } = params;
    const setName: string = `${keyName}${name}`;
    const obj = {
        dataType: typeof content,
        content: content,
        type: type,
        datetime: new Date().getTime()
    };
    if (type) window.sessionStorage.setItem(setName, JSON.stringify(obj));
    else window.localStorage.setItem(setName, JSON.stringify(obj));
};

export const getStore = (params: paramsType) => {
    const { name } = params;
    const getName: string = `${keyName}${name}`;
    let obj, content;
    obj = window.sessionStorage.getItem(getName);
    if (validatenull(obj)) obj = window.localStorage.getItem(getName);
    if (validatenull(obj)) return;
    try {
        obj = JSON.parse(obj as string);
    } catch {
        return obj;
    }
    if (obj.dataType == 'string') {
        content = obj.content;
    } else if (obj.dataType == 'number') {
        content = Number(obj.content);
    } else if (obj.dataType == 'boolean') {
        content = eval(obj.content);
    } else if (obj.dataType == 'object') {
        content = obj.content;
    }

    return content;
};
